package lei.h_java8特性;

/**
 * @className: JavaStream
 * @author: xl
 * @date: 2025/3/1 15:11
 * @Version: 1.0
 * @description:
 */

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamExample {
    public static void main(String[] args) {
        // 从集合创建 Stream
        List<String> list = Arrays.asList("Java", "Python", "C++", "JavaScript");
        Stream<String> streamFromList = list.stream();

        // 从数组创建 Stream
        String[] array = {"Apple", "Banana", "Cherry"};
        Stream<String> streamFromArray = Arrays.stream(array);

        // 直接创建 Stream
        Stream<String> directStream = Stream.of("One", "Two", "Three");


        /**
         * 常用 Stream 操作 中间流
         */

        //(1) 过滤 (filter)
        List<String> languages = Arrays.asList("Java", "Python", "C++", "JavaScript", "Go");
        // 过滤出长度大于 3 的字符串
        List<String> filtered = languages.stream()
                .filter(lang -> lang.length() > 3)
                .collect(Collectors.toList()); // Java 16+ 的 toList()，或者用 collect(Collectors.toList())
        System.out.println(filtered); // 输出: [Java, Python, JavaScript]


        /**
         *
         使用 map() 当：
         需要简单转换（如类型转换、属性提取）
         输入输出元素数量相同
         不需要处理嵌套集合
         使用 flatMap() 当：
         需要处理嵌套集合（List<List<T>>）
         需要将单个元素扩展为多个元素
         需要合并多个流
         需要过滤并展平数据（结合 filter）
         */
        //(2) 映射 (map)
        List<String> languages1 = Arrays.asList("Java", "Python", "C++");
        // 将每个字符串转换为大写
        List<String> upperCaseLanguages = languages1.stream()
                .map(String::toUpperCase)
                .collect(Collectors.toList());
        System.out.println(upperCaseLanguages); // 输出: [JAVA, PYTHON, C++]


        List<String> phrases = Arrays.asList("Hello world", "Java 8 Streams");

        // 拆分短语为单词
        List<String> words = phrases.stream()
                .flatMap(phrase -> Arrays.stream(phrase.split(" ")))
                .collect(Collectors.toList());
        // 结果: ["Hello", "world", "Java", "8", "Streams"]

        // 处理嵌套集合
        List<List<Integer>> numberLists = Arrays.asList(
                Arrays.asList(1, 2),
                Arrays.asList(3, 4, 5)
        );

        List<Integer> allNumbers = numberLists.stream()
                .flatMap(List::stream)
                .collect(Collectors.toList());
// 结果: [1, 2, 3, 4, 5]


        //(3) 排序 (sorted)
        List<Integer> numbers = Arrays.asList(5, 3, 9, 1, 4);

        // 对数字进行排序
        List<Integer> sortedNumbers = numbers.stream()
                .sorted()
                .collect(Collectors.toList());

        System.out.println(sortedNumbers); // 输出: [1, 3, 4, 5, 9]


        //(4) 聚合 (reduce)  归并
        List<Integer> numbers1 = Arrays.asList(1, 2, 3, 4, 5);

        // 计算所有数字的和
        int sum = numbers1.stream()
                .reduce(0, Integer::sum); // 0 是初始值

        System.out.println(sum); // 输出: 15


        //(5) 去重 (distinct)
        List<Integer> numbers2 = Arrays.asList(1, 2, 2, 3, 3, 3);

        // 去重
        List<Integer> distinctNumbers = numbers2.stream()
                .distinct()
                .collect(Collectors.toList());

        System.out.println(distinctNumbers); // 输出: [1, 2, 3]


        //(6) 限制和跳过 (limit 和 skip)
        List<Integer> numbers3 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        // 跳过前 2 个元素，取接下来的 3 个元素
        List<Integer> result = numbers3.stream()
                .skip(2)
                .limit(3)
                .collect(Collectors.toList());
        System.out.println(result); // 输出: [3, 4, 5]


        //（7）匹配 (anyMatch, allMatch, noneMatch)
        List<String> languages2 = Arrays.asList("Java", "Python", "C++", "JavaScript");
        // anyMatch
        boolean anyMatch = languages2.stream()
                .anyMatch(lang -> lang.startsWith("J"));
        System.out.println("anyMatch: " + anyMatch); // true

        // allMatch
        boolean allMatch = languages2.stream()
                .allMatch(lang -> lang.length() > 3);
        System.out.println("allMatch: " + allMatch); // true

        // noneMatch
        boolean noneMatch = languages2.stream()
                .noneMatch(lang -> lang.startsWith("Z"));
        System.out.println("noneMatch: " + noneMatch); // true


        //(8) 收集 (collect)
        List<String> languages3 = List.of("Java", "Python", "C++", "JavaScript");

        // 将列表转换为 Map，键为字符串，值为字符串长度
        Map<String, Integer> languageLengthMap = languages3.stream()
                .collect(Collectors.toMap(lang -> lang, String::length));

        System.out.println(languageLengthMap); // 输出: {Java=4, Python=6, C++=3, JavaScript=10}


        /**
         * 并行流 (Parallel Stream)
         */

        List<Integer> numbers4 = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
        // 使用并行流计算平方和
        int sumOfSquares = numbers4.parallelStream()
                .mapToInt(num -> num * num)
                .sum();
        System.out.println(sumOfSquares); // 输出: 285


    }
}


